<template>
  <div>
    <!--面包屑-->
    <el-breadcrumb separator="/" style="padding-left: 10px;padding-bottom: 10px;font-size: 12px">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <!--      <el-breadcrumb-item><a href="/">系统管理</a></el-breadcrumb-item>-->
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!--用户列表卡片-->
    <el-card class="box-card">
      <el-form :inline="true" :model="userVO" class="demo-form-inline" label-width="70px">
        <el-form-item label="部门">
          <el-select
            v-model="userVO.deptId"
            placeholder="请选择所属部门"
          >
            <el-option
              v-for="department in departments"
              :label="department.name"
              :key="department.id"
              :value="department.id"
            >
              <span style="float: left">{{ department.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                <el-tag size="small" effect="plain" type="success">
                  {{ department.total }}人
                </el-tag>
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="姓名" label-width="70px">
          <el-input clearable v-model="userVO.username" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" label-width="70px">
          <el-input clearable v-model="userVO.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio v-model="userVO.sex" label="0">男</el-radio>
          <el-radio v-model="userVO.sex" label="1">女</el-radio>
          <el-radio v-model="userVO.sex" label>全部</el-radio>
        </el-form-item>
        <el-form-item label="电话" label-width="70px">
          <el-input clearable v-model="userVO.phone" placeholder="请输入电话"></el-input>
        </el-form-item>

        <el-form-item style="margin-left: 30px">
          <el-button icon="el-icon-refresh" @click="reset">重置</el-button>
          <el-button type="primary" icon="el-icon-search" @click="getUsers">查询</el-button>
          <el-button type="success" icon="el-icon-plus" @click="addDialogVisible=true">添加</el-button>
        </el-form-item>
      </el-form>
      <!--      表格内容显示区域-->
      <el-table
        v-loading="loading"
        :data="userList"
        border
        max-height="600"
        style="width: 100%;">
        <el-table-column
          prop="id"
          label="#"
          width="50">
        </el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          width="110">
        </el-table-column>
        <el-table-column prop="sex" :formatter="showSex" label="性别" width="80">
          <template slot-scope="scope">
            <el-tag size="small" type="success" v-if="scope.row.sex===0">男</el-tag>
            <el-tag size="small" type="warning" v-else>女</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="roleName"
          label="岗位"
          width="150">
        </el-table-column>
        <el-table-column
          prop="deptName"
          label="部门"
          width="120">
        </el-table-column>
        <el-table-column
          prop="phone"
          label="电话"
          width="180">
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          width="180">
        </el-table-column>
        <el-table-column
          prop="address"
          label="地址"
          width="180">
        </el-table-column>
        <el-table-column
          sortable
          prop="birth"
          label="生日"
          width="150">
        </el-table-column>
        <el-table-column
          label="操作"
          width="120"
          fixed="right">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="edit(scope.row)"></el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="padding-top:15px"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="current"
        :page-sizes="[6, 12, 30, 50]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>

      <el-dialog title="添加用户" @close="closeDialog" :visible.sync="addDialogVisible" width="50%;">
        <!-- 表单 -->
        <span>
          <el-form
            :model="addForm"
            :label-position="labelPosition"
            :rules="addFormRules"
            ref="addFormRef"
            label-width="80px"
          >
            <el-row>
              <el-col :span="10">
                <div class="grid-content bg-purple">
                  <el-form-item label="用户名" prop="username">
                    <el-input v-model="addForm.username"></el-input>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple-light">
                  <el-form-item label="角色" prop="roleId">
                    <el-select v-model="addForm.roleId" placeholder="请选择用户角色">
                      <el-option
                        v-for="role in roles"
                        :key="role.id"
                        :label="role.name"
                        :value="role.id"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="10">
                <div class="grid-content bg-purple">
                  <el-form-item label="密码" prop="password">
              <el-input v-model="addForm.password"></el-input>
            </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple-light">
                  <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="addForm.sex">
                      <el-radio :label="0">男</el-radio>
                      <el-radio :label="1">女</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="10">
                <div class="grid-content bg-purple">
            <el-form-item label="手机" prop="phone">
              <el-input v-model="addForm.phone"></el-input>
            </el-form-item>
                  </div>
              </el-col>
              <el-col :span="10">
                <div class="grid-content bg-purple-light">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="addForm.email"></el-input>
            </el-form-item>
                  </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="10">
                <div class="grid-content bg-purple">
            <el-form-item label="地址" prop="address">
              <el-input v-model="addForm.address"></el-input>
            </el-form-item>
                  </div>
              </el-col>
              <el-col :span="10">
                <div class="grid-content bg-purple-light">
            <el-form-item prop="birth" label="生日">
                <el-date-picker
                  type="date"
                  placeholder="选择出生日期"
                  value-format="yyyy-MM-dd"
                  v-model="addForm.birth"
                  style="width: 100%;"
                ></el-date-picker>

            </el-form-item>
                  </div>
              </el-col>
            </el-row>


          </el-form>
        </span>

        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="addUser"
            :loading="btnLoading"
            :disabled="btnDisabled"
          >确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editClose">
        <span>
          <el-form
            :model="editForm"
            :label-position="labelPosition"
            :rules="addFormRules"
            ref="editFormRef"
            label-width="80px"
          >
            <el-row>
              <el-col :span="10">
                <div class="grid-content bg-purple">
                  <el-form-item label="用户名" prop="username">
                    <el-input v-model="editForm.username" :disabled="true"></el-input>
                    <el-input
                      type="hidden"
                      v-model="editForm.id"
                      :disabled="true"
                      style="display:none;"
                    ></el-input>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple-light">
                  <el-form-item label="部门" prop="departmentId">
                    <el-select v-model="editForm.departmentId" placeholder="请选择所属部门">
                      <el-option
                        v-for="department in departments"
                        :key="department.id"
                        :label="department.name"
                        :value="department.id"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="10">
                <div class="grid-content bg-purple">
                  <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="editForm.nickname"></el-input>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple-light">
                  <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="editForm.sex">
                      <el-radio :label="1">帅哥</el-radio>
                      <el-radio :label="0">美女</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>

            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editForm.email"></el-input>
            </el-form-item>
            <el-form-item label="联系方式" prop="phoneNumber">
              <el-input v-model="editForm.phone"></el-input>
            </el-form-item>
            <el-form-item prop="birth" label="生日">
              <el-col :span="11">
                <el-date-picker
                  type="date"
                  value-format="yyyy年MM月dd日"
                  placeholder="选择出生日期"
                  v-model="editForm.birth"
                  style="width: 100%;"
                ></el-date-picker>
              </el-col>
            </el-form-item>
          </el-form>
        </span>

        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="updateUser"
            :loading="btnLoading"
            :disabled="btnDisabled"
          >确 定</el-button>
        </span>
      </el-dialog>

    </el-card>
  </div>
</template>

<script>
import { getUserList,add } from '../../api/users'
import { getDept } from '../../api/department'
import { getAllRoles } from '../../api/role'

export default {
  name: 'Users',
  data () {
    const checkEmail = (rule, value, callback) => {
      const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
      if (!value) {
        return callback(new Error('邮箱不能为空'))
      }
      setTimeout(() => {
        if (mailReg.test(value)) {
          callback()
        } else {
          callback(new Error('请输入正确的邮箱格式'))
        }
      }, 100)
    }
    const checkPhone = (rule, value, callback) => {
      const phoneReg = /^1[34578]\d{9}$$/
      if (!value) {
        return callback(new Error('电话号码不能为空'))
      }
      setTimeout(() => {
        if (!Number.isInteger(+value)) {
          callback(new Error('请输入数字值'))
        } else {
          if (phoneReg.test(value)) {
            callback()
          } else {
            callback(new Error('电话号码格式不正确'))
          }
        }
      }, 100)
    }
    return {
      //当前页
      current: 1,
      size: 6,
      total: 100,
      loading: true,
      departments: [],
      roles: [],
      btnLoading: false,
      addDialogVisible: false,
      editDialogVisible: false, //修改对话框
      btnDisabled: false,
      labelPosition: 'right', //lable对齐方式
      addFormRules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 10,
            message: '长度在 2 到 10 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 12,
            message: '长度在 3 到 12 个字符',
            trigger: 'blur'
          }
        ],
        roleId: [
          {
            required: true,
            message: '请选择角色',
            trigger: 'blur'
          }
        ],
        sex: [{
          required: true,
          message: '请选择性别',
          trigger: 'blur'
        }],
        birth: [{
          required: true,
          message: '请填写出生日期',
          trigger: 'blur'
        }],
        email: [{
          required: true,
          validator: checkEmail,
          trigger: 'blur'
        }],
        phone: [
          {
            required: true,
            message: '请输入联系方式',
            validator: checkPhone,
            trigger: 'blur'
          }
        ],
        address: [
          {
            required: true,
            message: '请输入地址',
            trigger: 'blur'
          }
        ]
      },
      addForm: {
        username: '',
        address: '',
        password: '',
        email: '',
        phone: '',
        sex: '',
        birth: '',
        roleId: ''
      },
      editForm: {}, //更新表单
      userVO: {
        username: '',
        email: '',
        sex: '',
        phone: '',
        deptId: '',
      },
      userList: [],
      // 角色对话框的可见性
      dialogVisible: false,
      // 用户拥有的角色
      hasRoleIds: [],
      // 保存当前授权的用户ID
      uid: '',
    }
  },
  created () {
    //创建组件的时候调用查询所有用户的方法
    this.getRoles()
    this.getUsers()
    this.getDepartments()
    setTimeout(() => {
      this.loading = false
    }, 500)
  },
  methods: {
    reset () {
      this.userVO = {
        username: '',
        email: '',
        sex: '',
        phone: '',
        deptId: '',
      }
    },
    // 每页条数改变
    handleSizeChange (val) {
      this.size = val
      this.getUsers()
      // console.log(`每页 ${val} 条`);
    },
    // 当前页码改变
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`);
      this.current = val
      this.getUsers()
    },
    async getUsers () {

      const res = await getUserList(this.current, this.size, this.userVO)
      console.log(res)
      if (res.code !== 200) {
        return this.$message.error('获取用户列表失败:' + res.message)
      }
      this.userList = res.data.userList
      this.total = res.data.total
    },
    /**
     * 加载所有部门
     */
    async getDepartments () {
      const res = await getDept()
      console.log(res)
      if (res.code != 200) {
        return this.$message.error('获取部门列表失败:' + res.message)
      }
      this.departments = res.data.dept
    },
    //加载所有角色
    async getRoles () {
      const res = await getAllRoles()
      console.log(res)
      if (res.code != 200) {
        return this.$message.error('获取角色列表失败:' + res.message)
      }
      this.roles = res.data.roles
    },
    /**
     * 显示用户性别
     */
    showSex (row, column) {
      return row.sex == 0 ? ' 男' : '女'
    },
    closeDialog () {
      this.$refs.addFormRef.clearValidate()
      this.addForm.birth = ''
      this.addForm = {}
    },
    async addUser () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return
        } else {
          this.btnLoading = true
          this.btnDisabled = true
          const res = await add(this.addForm)
          if (res.code==200) {
            this.$notify.success({
              title: '操作成功',
              message: '用户添加成功',
            })
            this.addForm = {}
            await this.getUsers()
          } else {
            this.$message.error('用户添加失败:' + res.message)
          }
          this.addDialogVisible = false
          this.btnLoading = false
          this.btnDisabled = false
        }
      })
    },
    /**
     * 修改用户信息
     */
    edit (row) {
      this.editForm = JSON.parse(JSON.stringify(row))
      this.editDialogVisible = true
    },
  }
}
</script>

<style scoped>

</style>
